// 档级管理
import { ExclamationCircleFilled } from '@ant-design/icons';
import { Button, Form, Input, InputNumber, Modal, Select, Space, Table, notification } from 'antd';
import { useEffect, useState } from 'react';
import { request } from 'umi';
function GetTreeData(data) {
  let TreeData = [];
  let map = new Map(); //存在id,对应所在的内存地址
  // console.log(map);
  let outputObj, pid;
  for (let i = 0; i < data.length; i++) {
    pid = data[i].pid;
    if (map.has(pid)) {
      //存在，将些信息，加入到对应id=pid的对象上的children
      if (!map.get(pid).children) map.get(pid).children = [];
      let obj = new Object(data[i]);
      map.get(pid).children.push(obj);
      map.set(data[i].id, obj);
      // console.log(map);
    } else if (!map.has(pid) && pid === 0) {
      //这里处理pid不存在，且pid 为0的处理，pid不存在，且不为0的，程序不考虑这种情况
      outputObj = new Object(data[i]);
      TreeData.push(outputObj);
      map.set(data[i].id, outputObj);
      // console.log(map);
    }
  }
  return TreeData;
}

function tops(data) {
  let topArr = [];
  let arrObj = {};
  for (let item of data) {
    if (item.children) {
      arrObj = {
        title: item.title,
        id: item.id,
      };
      topArr.push(arrObj);
    }
  }
  return topArr;
}
function topss(data) {
  let topArr = [];
  for (let item of data) {
    if (item.children) {
      topArr.push(item);
    }
  }
  return topArr;
}
export default function Stage() {
  // 数据请求
  let [data, setData] = useState([]);
  let [open, setOpen] = useState(false);
  let [topTitle, setTop] = useState([]);
  let [opens, setOpens] = useState(false);
  let [edid, setId] = useState(0);
  let [edStatus, setStatus] = useState(0);
  const { confirm } = Modal;
  const columns = [
    {
      title: '序号',
      dataIndex: 'id',
      key: 'id',
      width: '80px',
      align: 'center',
    },
    {
      title: '档级名称',
      dataIndex: 'title',
      key: 'id',
      align: 'center',
    },
    {
      title: '岗位薪资',
      dataIndex: 'money',
      key: 'id',
      align: 'center',
    },
    {
      title: '安全质量奖',
      dataIndex: 'safe',
      key: 'id',
      align: 'center',
    },
    {
      title: '岗位津贴',
      dataIndex: 'station',
      key: 'id',
      align: 'center',
    },
    {
      title: '薪资区间',
      dataIndex: 'between',
      key: 'id',
      align: 'center',
    },
    {
      title: '绩效薪资',
      dataIndex: 'performance',
      key: 'id',
      align: 'center',
    },
    {
      title: '操作',
      key: 'id',
      align: 'center',
      render: (e) => (
        <Space size="middle">
          <Button
            type="primary"
            style={{ backgroundColor: '#409EFF' }}
            onClick={() => {
              setOpens(true);

              console.log(e);
              let faa = '';
              function dei(afts) {
                for (let fath of afts) {
                  console.log(fath);
                  if (fath.children) {
                    for (let item of fath.children) {
                      if (e.id === fath.id) {
                        setId(e.id)
                        setStatus(0)
                        setTimeout(() => {
                          forms.setFieldsValue({
                            company: '顶级',
                            title: e.title,
                            money: e.money,
                            safe: e.safe,
                            station: e.station,
                            between: e.between,
                            performance: e.performance,
                          });
                          console.log(forms);
                        }, 100);
                      }
                      dei(fath.children)
                    }
                    
                  } else {
                    if (e.id === fath.id) {
                      for (let ins of data) {
                        if (ins.children) {
                          for (let top of ins.children) {
                            if (top.id === e.id) {
                              setId(e.id)
                              setStatus(e.pid)
                              setTimeout(() => {
                                forms.setFieldsValue({
                                  company: ins.title,
                                  title: e.title,
                                  money: e.money,
                                  safe: e.safe,
                                  station: e.station,
                                  between: e.between,
                                  performance: e.performance,
                                });
                                console.log(forms);
                              }, 100);
                            }
                          }
                        }
                      }
                    }
                    
                  }
                }
              }
              dei(data)
              forms.resetFields();
              
              console.log(faa);
            }}
          >
            编辑
          </Button>
          <Button
            type="primary"
            danger
            style={{ backgroundColor: '#F56C6C' }}
            onClick={() => {
              console.log(e.id);
              confirm({
                title: '确定下架该项目?',
                icon: <ExclamationCircleFilled />,
                content: '请确认后操作',
                onOk() {
                  console.log('OK');
                  request('/api/grade/index/del', {
                    method: 'POST',
                    data: {
                      id: e.id,
                    },
                    skipErrorHandler: true,
                  }).then((res) => {
                    console.log(res);
                    // 操作成功后数据更新
                    upDatas();
                    notification['success']({
                      message: `操作成功`,
                    });
                  });
                },
                onCancel() {
                  console.log('Cancel');
                },
              });
            }}
          >
            删除
          </Button>
        </Space>
      ),
      align: 'center',
    },
  ];
  function upDatas(){
    request('/api/grade/index/index', {
      params: {
        // status: 1,
      },
      skipErrorHandler: true,
    }).then((res) => {
      console.log(res);
      setData(GetTreeData(res.list));
    });
  }
  useEffect(() => {
    request('/api/grade/index/index', {
      params: {
        // status: 1,
      },
      skipErrorHandler: true,
    }).then((res) => {
      console.log(res);
      setData(GetTreeData(res.list));
      console.log(tops(topss(res.list)));
      setTop(tops(topss(res.list)));
    });
  }, []);
  console.log(data);
  const [form] = Form.useForm();
  const [forms] = Form.useForm();
  function finish(values) {
    console.log('ok');
    console.log(values);
    request('/api/grade/index/add', {
      method: 'POST',
      data: {
        pid: values.company,
        title: values.title,
        money: values.money || 0,
        safe: values.safe || 0,
        station: values.station || 0,
        between: values.between || 0,
        performance: values.performance || 0,
      },
      skipErrorHandler: true,
    }).then((res) => {
      console.log(res);
      if (res.code === 1) {
        notification['success']({
          message: `操作成功`,
          // description: '可在回收站中进行查看',
        });
        setOpen(false);
        upDatas()
      } else {
        notification['error']({
          message: `操作失败`,
          description: '请稍后重试',
        });
        setOpen(false);
      }
    });
  }
  function unfinish() {
    console.log('no');
    notification['error']({
      message: `请完善档级信息`,
      // description: '可在回收站中进行查看',
    });
  }
  function finishs(values) {
    console.log('ok');
    console.log(values);
    console.log(edid);
    console.log(edStatus);
    request('/api/grade/index/edit', {
      params: {
        id:edid,
        pid: edStatus,
        title: values.title,
        money: values.money || 0,
        safe: values.safe || 0,
        station: values.station || 0,
        between: values.between || 0,
        performance: values.performance || 0,
      },
      skipErrorHandler: true,
    }).then((res) => {
      console.log(res);
      setOpens(false)
      if(res.code === 1){
        notification['success']({
          message: `操作成功`,
          // description: '可在回收站中进行查看',
        });
        upDatas()
      }
    });
  }
  function unfinishs(values) {
    console.log('no');
    console.log(values);
    console.log(edid);
    console.log(edStatus);
    notification['error']({
      message: `请完善档级信息`,
      // description: '可在回收站中进行查看',
    });
  }

  return (
    <div>
      {/* <div style={{ fontWeight: '400', fontSize: '24px' }}>档级管理</div> */}
      <Button
        type="primary"
        style={{ backgroundColor: '#0052CC' }}
        onClick={() => {
          setOpen(true);
          form.resetFields();
        }}
      >
        新增
      </Button>
      <Table  rowKey="id"  columns={columns} dataSource={data} bordered={true} />
      {/* 新增窗口 */}
      <Modal
        title="添加档级"
        centered
        htmlType="submit"
        maskClosable={false}
        open={open}
        onOk={async () => {
          const formData = form.getFieldValue();
          console.log(formData);
          form.submit();
        }}
        onCancel={() => setOpen(false)}
        width={650}
      >
        <Form
          labelCol={{ span: 5 }}
          style={{ marginTop: '30px' }}
          validateTrigger={['onBlur', 'onChange']}
          onFinish={finish}
          onFinishFailed={unfinish}
          name="addForm"
          form={form}
        >
          <Form.Item
            label="选择档级"
            name="company"
            rules={[{ required: true, message: '请选择档级' }]}
          >
            <Select
              placeholder="请选择档级"
              fieldNames={{ label: 'title', value: 'id' }}
              options={topTitle || []}
            />
          </Form.Item>
          <Form.Item
            label="档级名称"
            name="title"
            rules={[{ required: true, message: '请填写档级名称', validateTrigger: 'onBlur' }]}
          >
            <Input placeholder="请输入档级名称" />
          </Form.Item>
          <Form.Item
            label="岗位薪资"
            name="money"
            rules={[{ required: true, message: '请填写岗位薪资' }]}
          >
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="安全质量奖"
            name="safe"
            rules={[{ required: true, message: '请填写安全质量奖', validateTrigger: 'onBlur' }]}
          >
            <Input placeholder="请输入安全质量奖" />
          </Form.Item>
          <Form.Item
            label="岗位津贴"
            name="station"
            rules={[{ required: true, message: '请填写岗位津贴', validateTrigger: 'onBlur' }]}
          >
            <Input placeholder="请输入岗位津贴" />
          </Form.Item>
          <Form.Item
            label="档级薪资区间"
            name="between"
            rules={[{ required: true, message: '请填写档级薪资区间', validateTrigger: 'onBlur' }]}
          >
            <Input placeholder="请输入档级薪资区间" />
          </Form.Item>
          <Form.Item
            label="绩效薪资"
            name="performance"
            rules={[{ required: true, message: '请填写绩效薪资', validateTrigger: 'onBlur' }]}
          >
            <Input placeholder="请输入绩效薪资" />
          </Form.Item>
        </Form>
      </Modal>
      {/* 编辑窗口 */}
      <Modal
        title="编辑档级"
        centered
        htmlType="submit"
        maskClosable={false}
        open={opens}
        onOk={async () => {
          const formData = forms.getFieldValue();
          console.log(formData);
          forms.submit();
        }}
        onCancel={() => setOpens(false)}
        width={950}
      >
        <Form
          labelCol={{ span: 3 }}
          style={{ marginTop: '30px' }}
          validateTrigger={['onBlur', 'onChange']}
          onFinish={finishs}
          onFinishFailed={unfinishs}
          name="editForm"
          form={forms}
        >
          <Form.Item
            label="选择档级"
            name="company"
            rules={[{ required: true, message: '请选择档级' }]}
          >
            <Input disabled placeholder="请输入档级名称" />
          </Form.Item>
          <Form.Item
            label="档级名称"
            name="title"
            rules={[{ required: true, message: '请填写档级名称', validateTrigger: 'onBlur' }]}
          >
            <Input placeholder="请输入档级名称" />
          </Form.Item>
          <Form.Item
            label="岗位薪资"
            name="money"
            rules={[{ required: true, message: '请填写岗位薪资' }]}
          >
            <InputNumber min={0} style={{ width: '100%' }} />
          </Form.Item>
          <Form.Item
            label="安全质量奖"
            name="safe"
            rules={[{ required: true, message: '请填写安全质量奖', validateTrigger: 'onBlur' }]}
          >
            <Input placeholder="请输入安全质量奖" />
          </Form.Item>
          <Form.Item
            label="岗位津贴"
            name="station"
            rules={[{ required: true, message: '请填写岗位津贴', validateTrigger: 'onBlur' }]}
          >
            <Input placeholder="请输入岗位津贴" />
          </Form.Item>
          <Form.Item
            label="档级薪资区间"
            name="between"
            rules={[{ required: true, message: '请填写档级薪资区间', validateTrigger: 'onBlur' }]}
          >
            <Input placeholder="请输入档级薪资区间" />
          </Form.Item>
          <Form.Item
            label="绩效薪资"
            name="performance"
            rules={[{ required: true, message: '请填写绩效薪资', validateTrigger: 'onBlur' }]}
          >
            <Input placeholder="请输入绩效薪资" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
}
